package com.darly.book.presenter;

import com.darly.book.model.remote.BookApi;
import com.darly.book.presenter.contract.SearchContract;
import com.darly.book.ui.base.RxPresenter;
import com.darly.book.utils.Constant;
import com.darly.book.utils.RxUtils;
import com.darly.dlcommon.common.dlog.DLog;
import com.darly.dlcommon.retrofit.RxjavaRetrofitRequestUtil;

import io.reactivex.disposables.Disposable;


public class SearchPresenter extends RxPresenter<SearchContract.View>
        implements SearchContract.Presenter {

    @Override
    public void searchHotWord() {
        Disposable disp = RxjavaRetrofitRequestUtil.getInstance().getWithHost(BookApi.class, Constant.API_BASE_URL)
                .getHotWordPackage()
                .map(bean -> bean.getHotWords())
                .compose(RxUtils::toSimpleSingle)
                .subscribe(
                        bean -> {
                            mView.finishHotWords(bean);
                        },
                        e -> {
                            DLog.e(e);
                        }
                );
        addDisposable(disp);
    }

    @Override
    public void searchKeyWord(String query) {
        Disposable disp = RxjavaRetrofitRequestUtil.getInstance().getWithHost(BookApi.class, Constant.API_BASE_URL)
                .getKeyWordPacakge(query)
                .map(bean -> bean.getKeywords())
                .compose(RxUtils::toSimpleSingle)
                .subscribe(
                        bean -> {
                            mView.finishKeyWords(bean);
                        },
                        e -> {
                            DLog.e(e);
                        }
                );
        addDisposable(disp);
    }

    @Override
    public void searchBook(String query) {
        Disposable disp = RxjavaRetrofitRequestUtil.getInstance().getWithHost(BookApi.class, Constant.API_BASE_URL)
                .getSearchBookPackage(query)
                .map(bean -> bean.getBooks())
                .compose(RxUtils::toSimpleSingle)
                .subscribe(
                        bean -> {
                            mView.finishBooks(bean);
                        },
                        e -> {
                            DLog.e(e);
                            mView.errorBooks();
                        }
                );
        addDisposable(disp);
    }
}
